package com.duguo.dynamicmvc.factory.stage;

import javassist.CtClass;
import javassist.CtMethod;

import com.duguo.dynamicmvc.factory.ControllerBuilder;
import com.duguo.dynamicmvc.factory.ControllerFactory;
import com.duguo.dynamicmvc.factory.WorkingModel;
import com.duguo.dynamicmvc.factory.processor.ProcessorHolder;
import com.duguo.dynamicmvc.factory.processor.controller.ControllerProcessor;
import com.duguo.dynamicmvc.factory.processor.model.ModelProcessor;
import com.duguo.dynamicmvc.factory.utils.javassist.FieldUtils;

public class SetupActionControllerStage implements Stage {

    public void execute(ControllerFactory controllerFactory) throws Exception {
        WorkingModel workingModel = controllerFactory.getWorkingModel();
        if (!workingModel.isHandlerController()) {
        	ControllerBuilder controllerBuilder = controllerFactory.getControllerBuilder();
			ProcessorHolder processorHolder = controllerBuilder.getProcessorHolder();
			ControllerProcessor controllerProcessor = processorHolder.getControllerProcessor();
        	ModelProcessor modelProcessor = processorHolder.getModelProcessor();
			controllerProcessor.setupDynamicControllerName(workingModel);
            boolean hasDynamicController = workingModel.getDynamicControllerName() != null;
            CtClass controllerCtClass = workingModel.getControllerCtClass();
			CtClass internalHandlerInterfaceCtClass = workingModel.getInternalHandlerInterfaceCtClass();
			if (hasDynamicController) {
                FieldUtils.setupField(controllerCtClass, internalHandlerInterfaceCtClass, "dynamicController");
            }
            CtMethod controllerHandlerCtMethod = workingModel.getControllerHandlerCtMethod();
			controllerProcessor.setupMultiActionControllerCtClass(
                    controllerCtClass,
                    controllerHandlerCtMethod,
                    hasDynamicController,workingModel.getStaticViewMapping(), internalHandlerInterfaceCtClass, 
                    workingModel.isSingleActionController(),controllerBuilder);
            if (workingModel.isDynamicController()) {
            	WorkingModel parentWorkModel = workingModel.getParentWorkModel();
				controllerProcessor.setupDynamicControllerParentHandler(controllerCtClass, parentWorkModel.getInternalHandlerInterfaceCtClass(),
                        parentWorkModel.getControllerHandlerCtMethod());
            }
            Class dynamicViewModelClass = controllerFactory.getDynamicViewModelClass();
			if(dynamicViewModelClass!=null){
				modelProcessor.makeDynamicViewModelImpl(controllerFactory,dynamicViewModelClass,controllerHandlerCtMethod);
            }
        }
    }
}
